#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import json
from typing import Any

from autoapi.common.base_file_handler import BaseFileHandler


class JsonHandler(BaseFileHandler):
    """JSON文件处理器"""
    
    @staticmethod
    def _load(file_obj, **kwargs) -> Any:
        """从文件对象加载JSON数据"""
        return json.load(file_obj, **kwargs)

    @staticmethod
    def _dump(data: Any, file_obj, **kwargs) -> None:
        """将数据写入JSON文件对象"""
        kwargs.setdefault('ensure_ascii', False)
        json.dump(data, file_obj, **kwargs)


def read_json_file(filepath: str, filename: str | None = None, **kwargs) -> dict:
    """
    读取 json 文件

    :param filepath: 文件路径
    :param filename: 文件名
    :param kwargs: 其他参数
    :return: JSON数据
    """
    return JsonHandler.read_file(filepath, filename, **kwargs)


def write_json_file(
    filepath: str | None = None,
    *,
    filename: str,
    data: Any = None,
    encoding: str = 'utf-8',
    mode: str = 'a',
    **kwargs,
) -> None:
    """
    写入 json 文件

    :param filepath: 文件路径
    :param filename: 文件名
    :param data: 要写入的数据
    :param encoding: 文件编码
    :param mode: 文件写入模式
    :param kwargs: 其他参数
    """
    if filepath is None:
        filepath = ''
    JsonHandler.write_file(filepath, filename, data, encoding=encoding, mode=mode, **kwargs)
